<template>
  <el-dialog
    :title="title"
    class="dialog-wrap"
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    width="600px"
  >
    <div class="dialog-cont">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="名称" prop="name" style="margin-bottom: 24px">
          <el-input
            type="input"
            style="width: 100%"
            v-model="ruleForm.name"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="IP地址" prop="ipAddr" class="ipAddr">
          <template>
            <span class=""></span>
            <ul class="ipAdress" style="width: 100%">
              <li v-for="(item, index) in ipAddressItem" :key="index">
                <input
                  ref="ipInput"
                  v-model="item.value"
                  type="text"
                  class="ipInputClass"
                  @input="checkIpVal(item)"
                  @keyup="turnIpPosition(item, index, $event)"
                />
                <div></div>
              </li>
            </ul>
            <div class="el-form-item__error" v-show="ipShow">
              请输入正确的IP地址
            </div>
          </template>
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >确 定</el-button
        >
      </span>
    </div>
  </el-dialog>
</template>
<script>
import {
  tbSysBlackAdd,
  tbSysBlackUpdate,
} from '@/api/admin/system/black-manage'
export default {
  data() {
    return {
      title: '新增',
      dialogVisible: false,
      ruleForm: {
        name: '',
        id: '',
        ipAddr: '',
      },
      rules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
      },
      ipAddressItem: [
        { value: '' },
        { value: '' },
        { value: '' },
        { value: '' },
      ],
      ipShow: false,
    }
  },
  watch: {
    ipAddressItem: {
      // 双向数据绑定的value
      handler: function (newVal, oldVal) {
        let str = ''
        for (const i in this.ipAddressItem) {
          str += this.formatter(this.ipAddressItem[i].value)
        }
        if (str === '000000000000') {
          str = ''
        }
      },
      deep: true,
    },
  },
  mounted() {
    this.$bus.$on('showDialogBlackAdd', (row) => {
      this.init(row)
    })
  },
  beforeDestroy() {
    this.$bus.$off('showDialogBlackAdd')
  },
  methods: {
    init(row) {
      if (row) {
        this.ruleForm.name = row.name
        this.ruleForm.ipAddr = row.ipAddr
        this.ruleForm.id = row.id
        if (row.ipAddr) {
          let arr = row.ipAddr.split('.')
          if (arr.length == 4) {
            arr.forEach((v, i) => {
              this.ipAddressItem[i].value = v
            })
          }
        }
      } else {
        this.ruleForm = this.$options.data().ruleForm
        this.ipAddressItem = this.$options.data().ipAddressItem
        this.$delete(this.ruleForm, 'id')
      }
      this.title = row ? '编辑' : '新增'
      this.dialogVisible = true
    },

    //保存
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.ipShow = this.ipAddressItem[0].value === ''
          if (!this.ipShow) {
            this.ruleForm.ipAddr = this.ipAddressItem
              .map((v) => v.value || '0')
              .join('.')
            this.title == '新增' ? this.add() : this.edit()
          }
        } else {
          this.ipShow = false
          this.ipAddressItem.forEach((e) => {
            if (e.value == '') {
              this.ipShow = true
            }
          })
        }
      })
    },
    async add() {
      await tbSysBlackAdd(this.ruleForm)
      this.successMsg('操作成功')
      this.$bus.$emit('refreshBlackList')
      this.dialogVisible = false
    },
    async edit() {
      await tbSysBlackUpdate(this.ruleForm)
      this.successMsg('操作成功')
      this.$bus.$emit('refreshBlackList')
      this.dialogVisible = false
    },
    formatter(val) {
      let value = val.toString()
      if (value.length === 2) {
        value = '0' + value
      } else if (value.length === 1) {
        value = '00' + value
      } else if (value.length === 0) {
        value = '000'
      }
      return value
    },
    // 检查ip输入为0-255
    checkIpVal(item) {
      //确保每个值都处于0-255
      let val = item.value
      // 处理非数字
      val = val.toString().replace(/[^0-9]/g, '')
      val = parseInt(val, 10)
      if (isNaN(val)) {
        val = ''
      } else {
        val = val < 0 ? 0 : val
        val = val > 255 ? 255 : val
      }
      item.value = val
    },
    // 光标位置判断
    turnIpPosition(item, index, event) {
      let self = this
      let e = event || window.event
      if (e.keyCode === 37) {
        // 左箭头向左跳转，左一不做任何措施
        if (index !== 0 && e.currentTarget.selectionStart === 0) {
          self.$refs.ipInput[index - 1].focus()
        }
      } else if (e.keyCode == 39) {
        // 右箭头向右跳转，右一不做任何措施
        if (
          index !== 3 &&
          e.currentTarget.selectionStart === item.value.toString().length
        ) {
          self.$refs.ipInput[index + 1].focus()
        }
      } else if (e.keyCode === 8) {
        // 删除键把当前数据删除完毕后会跳转到前一个input，左一不做任何处理
        if (index !== 0 && item.value === '') {
          self.$refs.ipInput[index - 1].focus()
        }
      } else if (e.keyCode === 13 || e.keyCode === 32 || e.keyCode === 190) {
        // 回车键、空格键、冒号均向右跳转，右一不做任何措施
        if (index !== 3) {
          self.$refs.ipInput[index + 1].focus()
        }
      } else if (item.value.toString().length === 3) {
        // 满3位，光标自动向下一个文本框
        if (index !== 3) {
          self.$refs.ipInput[index + 1].focus()
        }
      }
    },
  },
}
</script>
<style scoped lang="scss">
.dialog-wrap {
  .ipAdress {
    display: flex;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    width: 215px;
    height: 36px;
    padding-inline-start: 0px;
    margin-block-start: 0;
    margin-block-end: 0;
  }
  .ipAdress li {
    position: relative;
    height: 36px;
    margin: 0;
    list-style-type: none;
  }
  .ipInputClass {
    border: none;
    width: 49px;
    height: 23px;
    color: #606266;
    text-align: center;
    background: transparent;
  }
  .ipAdress li div {
    position: absolute;
    bottom: 8px;
    right: 0;
    border-radius: 50%;
    background: #505050;
    width: 2px;
    height: 2px;
  }
  /*只需要3个div*/
  .ipAdress li:last-child div {
    display: none;
  }
  /*取消掉默认的input focus状态*/
  .ipAdress input:focus {
    outline: none;
  }
}
</style>